//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.item;

import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.math.BigDecimal;
import javax.swing.*;
import org.jpgolay.gui.date.DateComboBox;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.me.util.MEUtility;

// Referenced classes of package org.jpgolay.me.item:
//            ItemCRUD, ItemAdvanceSearchGUI, Item
public class ItemPanelController {

    private class MouseClickList extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            actionAddressView();
        }

        MouseClickList() {
        }
    }

    public ItemPanelController(SearchBox deliverySearch, TableViewer deliveryTable, JDesktopPane desktop) {
        itemSearch = null;
        itemTable = null;
        itemSearchGui = null;
        calendarPeriod = null;
        dateComboBox = null;
        itemSearch = deliverySearch;
        itemTable = deliveryTable;
        this.desktop = desktop;
        changes = new PropertyChangeSupport(this);
        crud = new ItemCRUD();
        initSearch();
        initTable();
    }

    private void initSearch() {
        itemSearch.setList(new String[]{
                    "R\351f\351rence", "D\351signation", "Famille", "Fournisseur"
                });
        itemSearch.setVal("");
        itemSearch.setAdvanceSearch(getItemSearchGUI());
        itemSearch.getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        itemSearch.getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
    }

    private void initTable() {
        itemTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                });
        itemTable.setLastColumnNotEditable(0);
        itemTable.setCellEditable(false);
        itemTable.setAlternateColor(MEUtility.ITEM_LINE);
        itemTable.setColumnNames(new String[]{
                    "REFERENCE", "DESIGNATION", "FAMILLE", "FOURNISSEUR"
                });
        itemTable.setPreferredColumnSize(new int[]{
                    50, 50, 40, 40
                });
        actionSearch();
    }

    private ItemAdvanceSearchGUI getItemSearchGUI() {
        if (itemSearchGui == null) {
            itemSearchGui = new ItemAdvanceSearchGUI();
            itemSearchGui.getItemViewerPanel().clean();
            itemSearchGui.getItemViewerPanel().setReferenceLabel("Aucune donn\351es");
        }
        return itemSearchGui;
    }

    private void actionSearch() {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ref_code_barre, designation, familles_articles_id, fournisseurs_id FROM articles");
        switch (itemSearch.getSelectedIndex()) {
            case 0: // '\0'
                if (itemSearch.getVal().equals("")) {
                    sql.append(" ORDER BY ref_code_barre");
                } else {
                    sql.append(" WHERE ref_code_barre LIKE '");
                    sql.append(itemSearch.getVal());
                    sql.append("%' ORDER BY ref_code_barre");
                }
                break;

            case 1: // '\001'
                if (itemSearch.getVal().equals("")) {
                    sql.append(" ORDER BY designation");
                } else {
                    sql.append(" WHERE designation LIKE '");
                    sql.append(itemSearch.getVal());
                    sql.append("%' ORDER BY designation");
                }
                break;

            case 2: // '\002'
                if (itemSearch.getVal().equals("")) {
                    sql.append(" ORDER BY familles_articles_id");
                } else {
                    sql.append(" WHERE familles_articles_id LIKE '");
                    sql.append(itemSearch.getVal());
                    sql.append("%' ORDER BY familles_articles_id");
                }
                break;

            case 3: // '\003'
                if (itemSearch.getVal().equals("")) {
                    sql.append(" ORDER BY fournisseurs_id");
                } else {
                    sql.append(" WHERE fournisseurs_id LIKE '");
                    sql.append(itemSearch.getVal());
                    sql.append("%' ORDER BY fournisseurs_id");
                }
                break;

            default:
                if (itemSearch.getVal().equals("")) {
                    sql.append(" ORDER BY ref_code_barre");
                } else {
                    sql.append(" WHERE ref_code_barre LIKE '");
                    sql.append(itemSearch.getVal());
                    sql.append("%' ORDER BY ref_code_barre");
                }
                break;
        }
        Object data[][] = crud.getDataList(sql.toString());
        if (data != null) {
            itemTable.setData(data);
            itemTable.getTable().addMouseListener(new MouseClickList());
            itemSearch.setVal("");
            if (data.length == 1) {
                String old = barrecode;
                barrecode = (String) data[0][0];
                changes.firePropertyChange("barrecode", old, barrecode);
            }
        } else {
            itemTable.setData(getEmptyTable());
        }
    }

    private Object[][] getEmptyTable() {
        Object data[][] = new Object[3][4];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUN";
                data[i][2] = "ARTICLE";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
        }

        return data;
    }

    private void actionAddressView() {
        Item item = crud.getItemByPK((String) itemTable.getTable().getValueAt(itemTable.getTable().getSelectedRow(), 0));
        if (item != null) {
            getItemSearchGUI().getItemViewerPanel().setReferenceLabel("R\351f. : " + item.getId());
            getItemSearchGUI().getItemViewerPanel().setTaxLabel("Tva : " + item.getTvaId().toString());
            getItemSearchGUI().getItemViewerPanel().setDesignationLabel(item.getDesignation());
            getItemSearchGUI().getItemViewerPanel().setFamilyLabel("Famille : " + item.getFamillesArticlesId());
            getItemSearchGUI().getItemViewerPanel().setNotesLabel(item.getCommentaire());
            getItemSearchGUI().getItemViewerPanel().setSiteLabel("Stock : " + item.getEmplacement());
            getItemSearchGUI().getItemViewerPanel().setWebLabel("Web : " + item.getWeb());
            getItemSearchGUI().getItemViewerPanel().setBuyDateLabel("Date achat : " + item.getDate2());
            getItemSearchGUI().getItemViewerPanel().setSupplierLabel("Fournis. : " + item.getFournisseurId());
            getItemSearchGUI().getItemViewerPanel().setSpecialOfferLabel("Promo. : " + item.getPromotion().setScale(2, 4).toPlainString() + "%");
            getItemSearchGUI().getItemViewerPanel().setWeightPriceLabel("Prix pond\351r\351 : " + item.getPrixAchatPondere().setScale(2, 4).toPlainString());
            getItemSearchGUI().getItemViewerPanel().setMarginLabel(calculateMargin(item.getPriceList1(), item.getPrixRevient()));
            getItemSearchGUI().getItemViewerPanel().setCostLabel("Prix revient : " + item.getPrixRevient().setScale(2, 4).toPlainString());
            getItemSearchGUI().getItemViewerPanel().setDateLabel("Date vente : " + item.getDate());
            getItemSearchGUI().getItemViewerPanel().setSalePriceLabel("PRIX VENTE : " + item.getPriceList1().setScale(2, 4).toPlainString());
        }
    }

    private String calculateMargin(BigDecimal salesPrice, BigDecimal cost) {
        try {
            BigDecimal r = salesPrice.subtract(cost).divide(salesPrice.movePointLeft(2), 2, 4);
            return "Marge : " + r.toPlainString() + "%";
        } catch (RuntimeException e) {
            return "Marge : ";
        }
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }
    private SearchBox itemSearch;
    private TableViewer itemTable;
    private ItemAdvanceSearchGUI itemSearchGui;
    private CalendarPeriod calendarPeriod;
    private ItemCRUD crud;
    private JDesktopPane desktop;
    private String barrecode;
    private PropertyChangeSupport changes;
    private DateComboBox dateComboBox;
}
